package manager.com.ithei.edu.info.manager.service;


import manager.com.ithei.edu.info.manager.dao.BaseStudentDao;
import manager.com.ithei.edu.info.manager.dao.OtherStudentDao;
import manager.com.ithei.edu.info.manager.dao.StudentDao;
import manager.com.ithei.edu.info.manager.domain.Student;
import manager.com.ithei.edu.info.manager.factory.StudentFactory;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;

public class StudentService {
    // 创建StudentDao (库管)
    //private static StudentDao studentDao = new StudentDao();
    //private static OtherStudentDao studentDao = new OtherStudentDao();
    private static BaseStudentDao studentDao = StudentFactory.getStudentFactory();

    //查找所有学生对象
    public static Student[] findAllStudents() {
        Student[] stu = studentDao.findAllStudent();
        boolean bl = false;
        for (int i = 0; i < stu.length; i++) {
            if (stu[i] != null) {
                bl = true;
            }
        }
//        Arrays.stream(stu).forEach(st->{if(st!=null){bl=true;}});
        if (bl) {
            Arrays.sort(stu, new Comparator<Student>() {
                @Override
                public int compare(Student o1, Student o2) {
                    return o1.getSid().compareTo(o2.getSid());
                }
            });
            return stu;
        } else {
            return null;

        }
    }

    // 添加学生方法
    public boolean addStudent(Student stu) {
        // 2. 将学生对象, 传递给StudentDao 库管中的addStudent方法
        // 3. 将返回的boolean类型结果, 返还给StudentController
        return studentDao.addStudent(stu);
    }

    // 判断学号是否存在方法
    public boolean isExists(String id) {
        Student[] stus = studentDao.findAllStudent();
        // 假设id在数组中不存在
        boolean exists = false;
        // 遍历数组, 获取每一个学生对象, 准备进行判断
        for (int i = 0; i < stus.length; i++) {
            Student student = stus[i];
            //当对象不为空,且学号相同,则找到了返回true
            if (student != null && student.getSid().equals(id)) {
                exists = true;
                break;
            }
        }
        return exists;
    }

    public void deleteStudentByIdTwo(String id) {
        //删除指定学号的学生信息
        studentDao.deleteStudentByIdTwo(id);
    }

    public void setStudentByIdTwo(String id, Student stu) {
        //指定持久层(库管)设置指定学号的信息
        studentDao.setStudentByIdTwo(id, stu);
    }
}
